const fs = require('fs')
const fileService = require('../service/file.service')
const momentService = require('../service/moment.service')
const {  PICTURE_PATH } = require('../constants/file-path')
class MomentController {
  async create (ctx, next) {
    const userId = ctx.user.id
    const content = ctx.request.body.content
    // 2.把数据插入到数据库
    const result = await momentService.create(userId, content)
    ctx.body = result
  }
  async detail (ctx, next) {
    const momentId = ctx.params.momentId
    const result = await momentService.getMomentById(momentId)
    ctx.body = result
  }
  async list (ctx, next) {
    // 1.获取数据(offset/size)
    const { offset, size } = ctx.query;
    // 2.查询列表
    const result = await momentService.getMomentList(offset, size);
    ctx.body = result
  }
  async update (ctx, next) {
    // 1.获取参数
    const { momentId } = ctx.params
    const { content } = ctx.request.body
    // 2.修改内容
    const result = await momentService.update(content, momentId)
    ctx.body = result
  }
  async remove (ctx, next) {
    // 1.获取momentId
    const { momentId } = ctx.params
    // 2.修改内容
    const result = await momentService.remove(momentId)
    ctx.body = result
  }
  async addLabels (ctx, next) {
    const { labels } = ctx
    const { momentId } = ctx.params
    for (let label of labels) {
      const isExist = await momentService.hasLabel(momentId, label.id)
      if (!isExist) {
        await momentService.addLabel(momentId, label.id)
      }
    }
    ctx.body = '标签动态添加成功'
  }
  async fileInfo (ctx, next) {
    const { filename } = ctx.params
    const fileInfo = await fileService.getFileByFilename(filename)
    const { type } = ctx.query
    const types = ["small", "middle", "large"]
    if (types.some(item => item === type)) {
      filename = filename + '-' + type
    }
    ctx.response.set('content-type', fileInfo.mimetype)
    ctx.body = fs.createReadStream(`${PICTURE_PATH}/${filename}`)
  }
}
module.exports = new MomentController()